package work.chenxr.jasypt.utils;

import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;

/**
 * @Author Chenxr
 * @Date 2023/10/26
 * @Description 配置文件加密工具类
 */
public class JasyptUtil {
    /**
     * 加密
     */
    public static String encrypt(String content, String password) {
        return getStringEncryptor(password).encrypt(content);
    }

    /**
     * 解密
     */
    public static String decrypt(String content, String password) {
        return getStringEncryptor(password).decrypt(content);
    }

    /**
     * 取加密器
     */
    private static StringEncryptor getStringEncryptor(String password) {
        StandardPBEStringEncryptor stringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();

        config.setPassword(password);
        config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
        config.setKeyObtentionIterations(1000);
        config.setPoolSize(1);
        config.setProviderName(null);
        config.setProviderClassName(null);
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");

        stringEncryptor.setConfig(config);
        return stringEncryptor;
    }
}
